package com.dinadi.yidi.ui.activity;

import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.CooperationAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.CreativeHotspotDetailsBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.http.interfaces.IntegralChangeInterface;
import com.dinadi.yidi.ui.view.MyGridView;
import com.dinadi.yidi.ui.view.ShareMenuPopupWindow;
import com.dinadi.yidi.ui.view.ShowImageWebView;
import com.dinadi.yidi.utils.FormatCurrentData;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2017/4/14   展赛  活动详情
 * Time: 13:04
 */

public class ExhibitionMatchActivity extends BaseActivity {
    private View view;
    private TextView tvTitle, tv_hezuo, exhibition_match_title, surplus_num, time_competition, place_competition, sign_price;
    private Button btn_title_right;
    private ShowImageWebView activity_web;
    private ImageView cover_img, participate_in;
    private MyGridView gridview;
    private CooperationAdapter adapter;
    private View view_show;
    private String title, coverImg;
    /*判断是否登陆*/
    private boolean loginState;
    private ShareMenuPopupWindow selectImage;
    private int sharePosition;
    private String startTime, endTime, address, signPrice;
    /*展赛ID*/
    private String showId, subjectProductId, token, userId;


    @Override
    protected View getLayout() {
        view = LayoutInflater.from(this).inflate(R.layout.activity_daily_exhibition_match, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        activity_web = (ShowImageWebView) view.findViewById(R.id.activity_web);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        btn_title_right = (Button) view.findViewById(R.id.btn_title_right);
        btn_title_right.setBackgroundResource(R.drawable.product_details_icon_share);
        cover_img = (ImageView) view.findViewById(R.id.cover_img);
        exhibition_match_title = (TextView) view.findViewById(R.id.exhibition_match_title);
        surplus_num = (TextView) view.findViewById(R.id.surplus_num);
        time_competition = (TextView) view.findViewById(R.id.time_competition);
        place_competition = (TextView) view.findViewById(R.id.place_competition);
        sign_price = (TextView) view.findViewById(R.id.sign_price);
        participate_in = (ImageView) view.findViewById(R.id.participate_in);
        gridview = (MyGridView) view.findViewById(R.id.gridview);
        tv_hezuo = (TextView) view.findViewById(R.id.tv_hezuo);
        view_show = view.findViewById(R.id.view_show);

        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        activity_web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            // 网页加载结束
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                activity_web.getSettings().setJavaScriptEnabled(true);
                // web 页面加载完成，添加监听图片的点击 js 函数
                activity_web.setImageClickListner();
                //解析 HTML
                activity_web.parseHTML(view);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(ExhibitionMatchActivity.this, "请检查您的网络设置", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void initListener() {
        registerClickListener(btn_title_right, participate_in);
    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userId = SharePreferencesHelper.getInstance(this).getString("userId");
            token = SharePreferencesHelper.getInstance(this).getString("token");
            loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");
            SharePreferencesHelper.getInstance(this).putString("isRefresh", "no");
        }

    }

    private void getDailyExhibitionMatch() {
        CreativeHotspotDetailsBean bean = new CreativeHotspotDetailsBean();
        bean.setToken(token);
        bean.setSubjectId(subjectProductId);
        CommonInterface creativeHotspotDetailsInterface = new CommonInterface(this, dailyHttpListener);
        creativeHotspotDetailsInterface.getInterface("14008", JSON.toJSONString(bean));
    }

    private void getExhibitionMatch() {
        CreativeHotspotDetailsBean bean = new CreativeHotspotDetailsBean();
        bean.setToken(token);
        bean.setShowId(showId);
        bean.setUserId(userId);
        CommonInterface creativeHotspotDetailsInterface = new CommonInterface(this, httpListener);
        creativeHotspotDetailsInterface.getInterface("12004", JSON.toJSONString(bean));
    }

    @Override
    protected void initData() {

        activity_web.clearImgs();
        Intent intent = getIntent();
        showId = intent.getStringExtra("showId");
        loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");
        String everydayExhibitionMatch = intent.getStringExtra("everydayExhibitionMatch");
        subjectProductId = intent.getStringExtra("subjectProductId");
        token = SharePreferencesHelper.getInstance(this).getString("token");
        userId = SharePreferencesHelper.getInstance(this).getString("userId");
        if (everydayExhibitionMatch != null && everydayExhibitionMatch.equals("0")) {
            getDailyExhibitionMatch();
        } else {
            getExhibitionMatch();
        }
    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.btn_title_right:
                /*分享*/
                ShowPickDialog();
                break;
            case R.id.participate_in:
                /*我要参赛*/
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    Intent intent = new Intent(ExhibitionMatchActivity.this, RegistrationInformationActivity.class);
                    /*startTime,endTime,address,signPrice*/
                    intent.putExtra("startTime", startTime);
                    intent.putExtra("endTime", endTime);
                    intent.putExtra("address", address);
                    intent.putExtra("signPrice", signPrice);
                    intent.putExtra("title", title);
                    intent.putExtra("showId", showId);
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }


    /*每日站赛*/
    HttpListener dailyHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                String match = JsonUtil.getFieldValue(response, "match");
                showId = JsonUtil.getFieldValue(match, "showId");
                getExhibitionMatch();
            } else {
                toast("加载失败");
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("加载失败");
        }
    };
    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                title = JsonUtil.getFieldValue(response, "title");
                tvTitle.setText(title);
                exhibition_match_title.setText(title);
                String htmlPath = JsonUtil.getFieldValue(response, "detailHtml");
                activity_web.loadUrl(htmlPath);
                coverImg = JsonUtil.getFieldValue(response, "coverImg");
                if (!coverImg.equals("")) {
                    ImageUtils.loadImageView(ExhibitionMatchActivity.this, coverImg, cover_img);
                } else {
                    ImageUtils.loadImageView(ExhibitionMatchActivity.this, R.drawable.me_img_default, cover_img);
                }
                /*总人数*/
                String personNum = JsonUtil.getFieldValue(response, "personNum");
                /*报名人数*/
                String signNum = JsonUtil.getFieldValue(response, "signNum");
                if (signNum == null || "null".equals(signNum)) {
                    signNum = "0";
                }
                /*剩余人数*/
                int surplus = (Integer.parseInt(personNum)) - (Integer.parseInt(signNum));
                if (surplus == 0) {
                    surplus_num.setText("人数已满");
                } else {
                    surplus_num.setText("剩余" + surplus + "名");
                }

                /*时间显示*/
                startTime = JsonUtil.getFieldValue(response, "startTime");
                endTime = JsonUtil.getFieldValue(response, "endTime");
                //  String startDate = DateFormat.getDateInstance(DateFormat.FULL).format(FormatCurrentData.strToDateLong(startTime));
                //  String endDate = DateFormat.getDateInstance(DateFormat.FULL).format(FormatCurrentData.strToDateLong(endTime));
                // time_competition.setText(startDate.substring(0, startDate.length() - 3) + "-" + endDate.substring(0, endDate.length() - 3));
                String startDate = FormatCurrentData.getDate(startTime);
                String endDate = FormatCurrentData.getDate(endTime);
                time_competition.setText(startDate + " 到 " + endDate);

                address = JsonUtil.getFieldValue(response, "address");
                place_competition.setText(address);
                signPrice = JsonUtil.getFieldValue(response, "signPrice");
                if (signPrice.equals("0")) {
                    sign_price.setText("免费");
                } else {
                    sign_price.setText(signPrice);
                }
                /*是否报名 [int] 1-未报名 2-已报名*/
                String hasSign = JsonUtil.getFieldValue(response, "hasSign");
                /*活动状态 [int] 1-未开始 2-已开始 3-已结束*/
                String activeState = JsonUtil.getFieldValue(response, "activeState");

                /*未开始*/
                if (activeState.equals("1")) {
                    /*未报名*/
                    if (hasSign.equals("1")) {
                        /*可报名（人数未满）*/
                        if (surplus != 0) {
                            participate_in.setImageResource(R.drawable.activity_tab_participate);
                        } else {
                        /*不可报名（已报满）*/
                            participate_in.setOnClickListener(null);
                            participate_in.setImageResource(R.drawable.icon_to_be_full);
                        }
                    } else {
                    /*已报名*/
                        participate_in.setOnClickListener(null);
                        participate_in.setImageResource(R.drawable.activity_tab_sign_up);
                    }
                } else if (activeState.equals("2")) {
                /*已开始*/
                    participate_in.setOnClickListener(null);
                    participate_in.setImageResource(R.drawable.activity_icon_not_sign_up);
                } else {
                /*已结束*/
                    participate_in.setOnClickListener(null);
                    participate_in.setImageResource(R.drawable.activity_tab_is_over);
                }



        /*  *//*未报名*//*
                if (hasSign.equals("1")) {
                    *//*剩余人数*//*
                    if (surplus != 0) {
                        if (activeState.equals("1")) {
                            *//*未开始*//*
                            participate_in.setImageResource(R.drawable.activity_tab_participate);
                        } else if (activeState.equals("2")) {
                            *//*已开始*//*
                            participate_in.setOnClickListener(null);
                            participate_in.setImageResource(R.drawable.activity_icon_not_sign_up);
                        } else {
                            *//*已结束*//*
                            participate_in.setOnClickListener(null);
                            participate_in.setImageResource(R.drawable.activity_tab_is_over);
                        }
                    } else {
                    *//*不可报名（已报满）*//*
                        participate_in.setOnClickListener(null);
                        participate_in.setImageResource(R.drawable.icon_to_be_full);
                    }
                } else {
                    *//*已报名*//*
                    participate_in.setOnClickListener(null);
                    participate_in.setImageResource(R.drawable.activity_tab_sign_up);
                }*/
                /*合作方*/
                String sponsor = JsonUtil.getFieldValue(response, "sponsor");
                List<String> dataList = (List<String>) JsonUtil.parseJsonToList(sponsor,
                        new TypeToken<List<String>>() {
                        }.getType());

                if (dataList.size() != 0)

                {
                    ArrayList<HashMap<String, Object>> imagelist = new ArrayList<HashMap<String, Object>>();
                    // 使用HashMap将图片添加到一个数组中，注意一定要是HashMap<String,Object>类型的，因为装到map中的图片要是资源ID，而不是图片本身
                    // 如果是用findViewById(R.drawable.image)这样把真正的图片取出来了，放到map中是无法正常显示的
                    for (int i = 0; i < dataList.size(); i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("image", dataList.get(i));
                        imagelist.add(map);
                    }
                    adapter = new CooperationAdapter(ExhibitionMatchActivity.this, imagelist);
                    // 设置GridView的适配器为新建的simpleAdapter
                    gridview.setAdapter(adapter);
                } else

                {
                    tv_hezuo.setVisibility(View.GONE);
                    view_show.setVisibility(View.GONE);
                }
            } else

            {
                toast("加载失败");
            }

        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("加载失败");
        }
    };

    //弹出分享框
    private void ShowPickDialog() {
        if (selectImage == null) {
            selectImage = new ShareMenuPopupWindow(this);
            selectImage.setOnShareClickListener(shareClickListener);
        }
        selectImage.showAtLocation(this.findViewById(R.id.linearlayout_base), Gravity.BOTTOM, 0, 0);
    }

    private ShareMenuPopupWindow.OnShareClickListener shareClickListener = new ShareMenuPopupWindow.OnShareClickListener() {

        @Override
        public void onShareClick(int position) {
            screenshot(position);
        }
    };

    private void share() {
        ShareAction shareAction = new ShareAction(this);
        UMImage thumb = new UMImage(this, coverImg);
        UMWeb web = new UMWeb("http://yididesign.cn/share_show.html?show_id=" + showId);
        web.setTitle(title);//标题
        web.setThumb(thumb);  //缩略图
        web.setDescription("分享内容");//描述
        if (sharePosition == 1) {
            shareAction.setCallback(umShareListener).withMedia(web).share();


        } else {
            shareAction.setCallback(umShareListener).withMedia(web).share();

        }
        switch (sharePosition) {

            case 0:
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN); // 微信好友
                break;
            case 1:
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE);// 微信朋友圈
                break;

        }
        shareAction.share();
    }

    public void screenshot(int position) {
//        if (!LoadDialog.isShowProgressDialog()) {
//            LoadDialog.showProgressDialog(getActivity(), "制作分享数据...", false, false);
        sharePosition = position;
        share();

        //   }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
            selectImage.dismiss();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
            if (loginState == true) {
                IntegralChangeInterface.IntegralChange(ExhibitionMatchActivity.this, userId, token, "4", "1", "分享成功啦");
            } else {
                ToastUtil.showToast("分享成功啦");
            }
            selectImage.dismiss();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(ExhibitionMatchActivity.this, " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
            selectImage.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(ExhibitionMatchActivity.this, " 分享取消了", Toast.LENGTH_SHORT).show();
            selectImage.dismiss();
        }

    };

}
